<?php

namespace app\command\task\YoPoint;

use app\model\BaseModel;
use app\model\device\DeviceBaseModel;
use app\service\statistics\device\CountDrinkService;
use Symfony\Component\Process\Process;
use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * 同步友朋设备日流水
 */
class YoPointBrandAsyncDayTerminalProductJournal extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('同步友朋设备日流水')
            ->setDescription('同步友朋设备日流水');
    }

    protected function execute(Input $input, Output $output)
    {
        // 同步日流水
        $this->terminalProductJournalListSyancByDay();
        // 同步今日数据入统计库
        $serviceCountDrink = new CountDrinkService();
        $serviceCountDrink->syncToday();
    }

    /**
     * 设备日流水
     * @param string $date
     * @return void
     */
    private function terminalProductJournalListSyancByDay(string $date = '')
    {
        if ( empty($date) ) $date = date('Y-m-d');
        $deviceModel = new DeviceBaseModel();
        $deviceModelWhere = [
            'data_source_from' => BaseModel::dataSourceFromYoPoint,
        ];
        $allDeviceList = $deviceModel
            ->getAllList($deviceModelWhere, 'id, uuid, name')
            ->data;
        if (empty($allDeviceList)) {
            $this->output->writeln('无设备');
            return;
        }

        $processFunc = function (array $command) {
            $process = new Process($command);
            $process->setTimeout(3600);
            return $process;
        };

        $processList = [];

        foreach ($allDeviceList as $value) {
            $deviceUUID = $value['uuid'];
            $this->output->writeln("device ID:" . $deviceUUID);
            $startDate = $date;
            $endDate = $date;
            $dateRange = "$startDate - $endDate";
            $this->output->writeln("dateRange:" . $dateRange);
            $runCommand = [
                'php', 'think', 'yoPointBrandTerminalProductProcess', "$deviceUUID",
                "$startDate", "$endDate"
            ];
            $processList[] = $processFunc($runCommand);
        }

        if (!empty($processList)) {
            $this->output->writeln('开始异步进程');

            $chunkList = array_chunk($processList, 10);
            foreach ( $chunkList as $key => $dealList ){
                $this->output->writeln("第".($key+1)."组开始");
                foreach ($dealList as $item) {
                    $item->start();
                    sleep(1);
                }
                foreach ($dealList as $item) {
                    $item->wait();
                    $this->output->writeln("子进程结束，退出码：" . $item->getExitCodeText());
                }
                sleep(2);
            }
        }

    }

}